package ru.aslanov.schedule.client.ds;

import com.smartgwt.client.data.*;
import com.smartgwt.client.rpc.RPCResponse;
import com.smartgwt.client.types.DSOperationType;
import com.smartgwt.client.types.FieldType;
import com.smartgwt.client.util.SC;
import ru.aslanov.schedule.client.i18n.I18nUtil;
import ru.aslanov.schedule.client.i18n.MyConstants;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by IntelliJ IDEA.
 * Created: Jan 29, 2010 7:01:16 PM
 *
 * @author Sergey Aslanov
 */
public class BaseDS extends DataSource{
    private static final String DATA_URL = "/ru.aslanov.schedule.schedule/smart-gwt-data";
    private String dataId;
    protected static final MyConstants cnt = I18nUtil.cnt();
    protected DataSourceField encodedKey;
    private InputLangProvider inputLangProvider;

    protected BaseDS(String id, String dataId, InputLangProvider inputLangProvider) {
        setID(id);
        this.dataId = dataId;
        this.inputLangProvider = inputLangProvider;

        setRecordXPath("/data/item");

        encodedKey = new DataSourceField("encodedKey", FieldType.TEXT);
        encodedKey.setPrimaryKey(true);
        encodedKey.setHidden(true);

        setOperations();
    }

    protected BaseDS(String id, InputLangProvider inputLangProvider) {
        this(id, id, inputLangProvider);
    }

    protected void setOperations() {
        setOperationBindings(getOperationBinding(DSOperationType.FETCH),
                getOperationBinding(DSOperationType.ADD),
                getOperationBinding(DSOperationType.UPDATE),
                getOperationBinding(DSOperationType.REMOVE));
    }

    private OperationBinding getOperationBinding(DSOperationType dsOperationType) {
        return new OperationBinding(dsOperationType, DATA_URL + "/" + dataId + "/" + dsOperationType);
    }

    protected Map getRequestParams() {
        final Map map = new HashMap();
        if (inputLangProvider != null && inputLangProvider.getInputLang() != null) {
            map.put("inputLang", inputLangProvider.getInputLang());
        }
        return map;
    }

    @Override
    protected Object transformRequest(DSRequest dsRequest) {
        dsRequest.setParams(getRequestParams());            
        return super.transformRequest(dsRequest);
    }

    @Override
    protected void transformResponse(DSResponse dsResponse, DSRequest dsRequest, Object o) {
        if (dsResponse.getStatus() != RPCResponse.STATUS_SUCCESS) {
            if (dsRequest.getOperationType() == DSOperationType.REMOVE) {
                SC.warn(I18nUtil.cnt().cannotDelete());
            } else if (dsRequest.getOperationType() == DSOperationType.UPDATE || dsRequest.getOperationType() == DSOperationType.ADD) {
                SC.warn(I18nUtil.cnt().finishedWithErrors());                
            }
        }
        super.transformResponse(dsResponse, dsRequest, o);
    }
}
